<template>
  <div class="app-container" @mousedown="handleMouseDown">
    <div>窗口拖动</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue'

const isKeyDown = ref(false)

const isDragging = ref(false)
const startX = ref(0)
const startY = ref(0)
const threshold = ref(5) // 拖动阈值

let onMouseMove: (ev: MouseEvent) => void
let onMouseUp: () => void

const handleMouseDown = (event: MouseEvent): void => {
  // 如果不是鼠标左键，则不执行任何操作
  if (event.button !== 0) return

  window.electron.ipcRenderer.invoke('start-drag')

  isKeyDown.value = true

  startX.value = event.clientX
  startY.value = event.clientY
  isDragging.value = false

  onMouseMove = (ev: MouseEvent): void => {
    if (isKeyDown.value) {
      window.electron.ipcRenderer.invoke('drag-window')

      const dx = ev.clientX - startX.value
      const dy = ev.clientY - startY.value
      if (Math.sqrt(dx * dx + dy * dy) > threshold.value) {
        isDragging.value = true
      }
    }
  }
  document.addEventListener('mousemove', onMouseMove)

  onMouseUp = (): void => {
    window.electron.ipcRenderer.invoke('stop-drag')
    isKeyDown.value = false
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', onMouseUp)
  }

  document.addEventListener('mousemove', onMouseMove)
  document.addEventListener('mouseup', onMouseUp)

  // 清理事件监听器
  onUnmounted(() => {
    if (onMouseMove) document.removeEventListener('mousemove', onMouseMove)
    if (onMouseUp) document.removeEventListener('mouseup', onMouseUp)
  })
}
</script>

<style scoped>
.app-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  user-select: none;
  border-radius: 50%;
  background-color: #fff;
}
</style>
